<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @tap="goToSearch">
        <img :src="logo" class="search-logo" />
        <text class="app-name">知医</text>
        <text class="iconfont icon-search"></text>
        <text class="placeholder">搜索医院/科室/医生</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-area" :style="{ top: `calc(${statusBarHeight}px + 20rpx)` }">
      <!-- 轮播图 -->
      <swiper class="banner-swiper" circular autoplay interval="3000" duration="500">
        <swiper-item v-for="(item, index) in bannerList" :key="index" @tap="handleBannerClick(item)">
          <view class="banner-item">
            <image :src="item.imageUrl" mode="aspectFill" class="banner-image"></image>
            <view class="banner-title">{{ item.title }}</view>
          </view>
        </swiper-item>
      </swiper>

      <!-- 快捷功能区 -->
      <view class="quick-functions-grid">
        <view
          class="function-item"
          v-for="(func, index) in quickFunctions"
          :key="index"
          @tap="handleQuickFunction(func)"
        >
          <view :class="['func-icon', func.class]">
            <image v-if="func.isImage" :src="func.icon" mode="aspectFit" class="func-image"></image>
            <text v-else class="iconfont" :class="func.icon"></text>
          </view>
          <text class="func-name">{{ func.name }}</text>
        </view>
      </view>

      <!-- 推荐内容区 -->
      <view class="recommendation-area">
        <view class="recommendation-section" v-for="(section, index) in recommendations" :key="index">
          <view class="section-header">
            <text class="section-title">{{ section.title }}</text>
            <text class="more-link" @tap="goToMore(section.type)">查看更多 ></text>
          </view>
          <view class="section-content">
            <text v-if="section.items.length === 0" class="no-data-placeholder">暂无{{ section.title }}数据</text>
            <!-- 这里可以放置具体医院、科室或医生的列表，未来可以根据section.type加载不同数据 -->
            <view v-else class="recommendation-list">
              <template v-if="section.type === 'hospital'">
                <view 
                  class="list-item"
                  v-for="(item, idx) in section.items" 
                  :key="item.id" 
                  @tap="goToHospitalDetail(item)"
                >
                  <image :src="config.staticUrl + (item.imgUrl || '/static/images/default-hospital.png')" mode="aspectFill" class="item-image"></image>
                  <view class="item-info">
                    <text class="item-name">{{ item.name }}</text>
                    <text class="item-detail">{{ item.hospitalGrade }} | {{ item.diseaseType }}</text>
                    <text class="item-address">{{ item.address }}</text>
                  </view>
                </view>
              </template>

              <template v-else-if="section.type === 'department'">
                <view 
                  class="list-item"
                  v-for="(item, idx) in section.items" 
                  :key="item.id" 
                  
                >
                  <view class="item-info no-image">
                    <text class="item-name">{{ item.name }}</text>
                    <text class="item-detail">{{ item.diseaseType }}</text>
                    <text class="item-snapshot">{{ item.snapshot }}</text>
                    <text class="item-count">{{ item.hospitals.length }}家医院</text>
                  </view>
                </view>
              </template>

              <template v-else-if="section.type === 'doctor'">
                <view 
                  class="list-item"
                  v-for="(item, idx) in section.items" 
                  :key="item.id" 
                  @tap="goToDoctorDetail(item)"
                >
                  <image :src="config.staticUrl + (item.imgUrl || '/static/images/default-avatar.png')" mode="aspectFill" class="item-image avatar"></image>
                  <view class="item-info">
                    <view class="item-name-title">
                      <text class="item-name">{{ item.name }}</text>
                      <text class="item-title">{{ item.jobTitle }}</text>
                    </view>
                    <text class="item-detail">{{ item.departmentName }} | {{ item.hospitalName }}</text>
                    <text class="item-specialty">擅长: {{ item.professionalExpertise || '暂无' }}</text>
                  </view>
                </view>
              </template>
            </view>
          </view>
        </view>
      </view>
	  
	  <!-- 咨询服务卡片 -->
	  <view class="consultation-card">
	    <view class="card-content">
	      <text class="card-title">需要咨询服务？</text>
	      <text class="card-subtitle">专业咨询人员随时待命</text>
	    </view>
	    <button class="contact-btn" @tap="contactService">联系咨询专员</button>
	  </view>	  
	  
    </view>
  </view>
</template>

<script>
import {getDicts} from "@/api/city.js"
import {getAccompanyingTherapistByIsadmin} from '@/api/peizhenshi.js'
import logoImg from '@/static/logo.png'
import { getHospitalByBiseaseType } from '@/api/hospital'
import { selectDepartmentAll } from '@/api/department'
import { selectDoctorByDepartmentId } from '@/api/doctor'
import config from '@/config'
// import shenImg from '@/static/img/身.png'
// import tiImg from '@/static/img/体.png'
// import jianImg from '@/static/img/健.png'
// import kangImg from '@/static/img/康.png'
// import wanImg from '@/static/img/万.png'
// import shiImg from '@/static/img/事.png'
// import ruImg from '@/static/img/如.png'
// import yiImg from '@/static/img/意.png'

export default {
  data() {
    return {
      statusBarHeight: 0,
      peizhenshiphone:[],
      diseaseList:[],
      bannerList: [
        {
          id: 1,
          imageUrl: '/static/banner/guide.jpg',
          type: 'guide',
          title: '就医指南'
        },
        {
          id: 2,
          imageUrl: '/static/banner/activity.jpg',
          type: 'activity',
          title: '活动通知'
        }
      ],
      logo: logoImg,
      quickFunctions: [
        { id: 'quick1', name: '预约挂号', icon: '/static/img/身.png', class: 'func-icon-image', isImage: true, path: '/pages/appointment/index' },
        { id: 'quick2', name: '智能问诊', icon: '/static/img/体.png', class: 'func-icon-image', isImage: true, path: '/pages/aichat/aichat' },
        { id: 'quick3', name: '用药提醒', icon: '/static/img/健.png', class: 'func-icon-image', isImage: true, path: '/pages/guide/reminder' },
        { id: 'quick4', name: '健康计算器', icon: '/static/img/康.png', class: 'func-icon-image', isImage: true, path: '/pages/guide/healthcalculator' },
        { id: 'quick5', name: '管理挂号', icon: '/static/img/万.png', class: 'func-icon-image', isImage: true, path: '/pages/appointment/manage' },
        { id: 'quick6', name: '陪诊服务', icon: '/static/img/事.png', class: 'func-icon-image', isImage: true, path: '/pages/service/Home' },
        { id: 'quick7', name: '医用工具', icon: '/static/img/如.png', class: 'func-icon-image', isImage: true, path: '/pages/guide/medical' },
        { id: 'quick8', name: '更多服务', icon: '/static/img/意.png', class: 'func-icon-image', isImage: true, path: '/pages/service/Home' }
      ],
      recommendations: [
        {
          type: 'hospital',
          title: '推荐医院',
          items: [] // Placeholder for future data
        },
        {
          type: 'department',
          title: '热门科室',
          items: [] // Placeholder for future data
        },
        {
          type: 'doctor',
          title: '名医推荐',
          items: [] // Placeholder for future data
        }
      ],
      searchHistory: [], // 新增：搜索历史
      config: config,  // 添加 config 到 data
      tabBarPaths: [
        '/pages/index/index',
        '/pages/medical/index',
        '/pages/service/Home',
        '/pages/community/index',
        '/pages/my/index'
      ] // 新增：tabBar页面的路径列表
    }
  },
  created() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight;
    
    var that = this;
    //陪诊师管理员
    getAccompanyingTherapistByIsadmin('1').then(res => {
      if (res.code == 200) {
        res.data.forEach(item => {
          that.peizhenshiphone.push(item.phone);
        })
      }
    });
    //取疾病
    getDicts('disease_type').then(res => {
      if (res.code == 200) {
        that.diseaseList = res.data;
      }
    });
  },
  onShow() {
    this.loadAllRecommendations();
  },
  methods: {
    loadSearchHistory() {
      this.searchHistory = uni.getStorageSync('searchHistory') || [];
    },
    filterAndLimitResults(items, keywords, fields) {
      if (!keywords || keywords.length === 0) {
        // 如果没有关键词，直接返回前2条
        return items.slice(0, 2);
      }

      const filtered = items.filter(item => {
        return keywords.some(keyword => {
          const lowerCaseKeyword = keyword.toLowerCase();
          return fields.some(field => {
            const value = item[field];
            return value && String(value).toLowerCase().includes(lowerCaseKeyword);
          });
        });
      });
      // 限制返回结果数量，最多2条
      return filtered.slice(0, 2);
    },
    async loadAllRecommendations() {
      this.loadSearchHistory();
      await this.fetchHospitalRecommendations();
      await this.fetchDepartmentRecommendations();
      await this.fetchDoctorRecommendations();
    },
    async fetchHospitalRecommendations() {
      try {
        const res = await getHospitalByBiseaseType();
        if (res.code === 200 && Array.isArray(res.data)) {
          const keywords = this.searchHistory;
          const fields = ['name', 'address', 'snapshot', 'hospitalGrade', 'diseaseType'];
          this.recommendations[0].items = this.filterAndLimitResults(res.data, keywords, fields);
        }
      } catch (error) {
        console.error('获取推荐医院失败:', error);
      }
    },
    async fetchDepartmentRecommendations() {
      try {
        const res = await selectDepartmentAll();
        if (res.code === 200 && Array.isArray(res.data)) {
          // 合并相同名称的科室 (与search.vue中的逻辑相同)
          const mergedDepartments = this.mergeDepartments(res.data);

          const keywords = this.searchHistory;
          const fields = ['name', 'snapshot', 'hospitalName', 'diseaseType'];
          this.recommendations[1].items = this.filterAndLimitResults(mergedDepartments, keywords, fields);
        }
      } catch (error) {
        console.error('获取热门科室失败:', error);
      }
    },
    async fetchDoctorRecommendations() {
      try {
        // 先获取所有科室，再获取所有医生
        const deptRes = await selectDepartmentAll();
        let allDoctors = [];
        if (deptRes.code === 200 && Array.isArray(deptRes.data)) {
          for (const dept of deptRes.data) {
            try {
              const res = await selectDoctorByDepartmentId(dept.id);
              if (res.code === 200 && Array.isArray(res.data)) {
                allDoctors = allDoctors.concat(res.data);
              }
            } catch (error) {
              console.error('获取科室医生失败:', error);
              continue;
            }
          }
        }

        const keywords = this.searchHistory;
        const fields = ['name', 'departmentName', 'hospitalName', 'jobTitle', 'professionalExpertise'];
        this.recommendations[2].items = this.filterAndLimitResults(allDoctors, keywords, fields);
      } catch (error) {
        console.error('获取名医推荐失败:', error);
      }
    },
    contactService() {
      this.showAndMakePhoneCall(this.peizhenshiphone);
    },
    showAndMakePhoneCall(phoneNumbers) {
      let stringPhones = phoneNumbers.map(number => number.toString());
      uni.showActionSheet({
        itemList: stringPhones,
        success: (res) => {
          if (res.tapIndex !== undefined) {
            const selectedPhoneNumber = stringPhones[res.tapIndex];
            this.makePhoneCall(selectedPhoneNumber);
          }
        },
        fail: (err) => {
          console.error("显示操作表失败:", err);
        },
      });
    },
    makePhoneCall(phoneNumber) {
      uni.makePhoneCall({
        phoneNumber: phoneNumber,
        success: () => {
          console.log(`成功拨打 ${phoneNumber}`);
        },
        fail: (err) => {
          console.error(`拨打 ${phoneNumber} 失败:`, err);
        },
      });
    },
    goToSearch() {
      uni.navigateTo({
        url: '/pages/index/search'
      })
    },
    handleBannerClick(item) {
      if (item.type === 'guide') {
        uni.navigateTo({
          url: '/pages/index/guide'
        })
      } else if (item.type === 'activity') {
        uni.navigateTo({
          url: '/pages/index/notification'
        })
      }
    },
    handleQuickFunction(func) {
      if (func.path) {
        if (this.tabBarPaths.includes(func.path)) {
          uni.switchTab({
            url: func.path
          })
        } else {
          uni.navigateTo({
            url: func.path
          })
        }
      } else {
        uni.showToast({
          title: `功能'${func.name}'待开发`,
          icon: 'none'
        })
      }
    },
    goToMore(type) {
      if (type === 'hospital') {
        uni.navigateTo({ url: '/pages/recommend/hospital' });
      } else if (type === 'department') {
        uni.navigateTo({ url: '/pages/recommend/department' });
      } else if (type === 'doctor') {
        uni.navigateTo({ url: '/pages/recommend/doctor' });
      }
    },
    mergeDepartments(departments) {
      const mergedMap = new Map();
      
      departments.forEach(dept => {
        if (!mergedMap.has(dept.name)) {
          mergedMap.set(dept.name, {
            id: dept.id, // Add department ID here
            name: dept.name,
            diseaseType: dept.diseaseType,
            snapshot: dept.snapshot,
            hospitals: [{
              hospitalName: dept.hospitalName,
              address: dept.address,
              id: dept.hospitalId
            }]
          });
        } else {
          const existing = mergedMap.get(dept.name);
          existing.hospitals.push({
            hospitalName: dept.hospitalName,
            address: dept.address,
            id: dept.hospitalId
          });
        }
      });
      
      return Array.from(mergedMap.values());
    },
    goToHospitalDetail(item) {
      if (item.id) {
        uni.navigateTo({
          url: `/pages/hospital/detail?id=${item.id}&biseaseType=${item.diseaseType || ''}`,
          success: (res) => {
            // 确保传递完整的医院数据，以便详情页展示
            res.eventChannel.emit('hospitalData', item);
          },
          fail: (err) => {
            console.error('跳转医院详情失败:', err);
            uni.showToast({ title: '跳转失败', icon: 'none' });
          }
        });
      } else {
        uni.showToast({ title: '医院ID缺失', icon: 'none' });
      }
    },
    goToDepartmentDetail(item) {
      // 科室详情页的逻辑可能需要根据实际情况调整
      // 例如，如果科室详情页需要hospitalId，则需要从item中获取
      // uni.navigateTo({
      //   url: `/pages/hospital/department?id=${item.id}`,
      //   success: (res) => {
      //       // 确保传递完整的科室数据，以便详情页展示
      //       res.eventChannel.emit('departmentData', item);
      //     },
      //     fail: (err) => {
      //       console.error('跳转科室详情失败:', err);
      //       uni.showToast({ title: '跳转失败', icon: 'none' });
      //     }
      // });
      uni.showToast({
        // title: '科室详情功能待开发',
        icon: 'none'
      });
    },
    goToDoctorDetail(item) {
      if (item.id) {
        uni.navigateTo({
          url: `/pages/hospital/doctor?id=${item.id}`,
          success: (res) => {
            // 确保传递完整的医生数据，以便详情页展示
            res.eventChannel.emit('doctorData', item);
          },
          fail: (err) => {
            console.error('跳转医生详情失败:', err);
            uni.showToast({ title: '跳转失败', icon: 'none' });
          }
        });
      } else {
        uni.showToast({ title: '医生ID缺失', icon: 'none' });
      }
    }
  }
}
</script>

<style>
page {
  background-color: #F5F6FA;
  height: 100vh; /* 新增：页面高度填充视口 */
  overflow: hidden; /* 新增：阻止页面滚动 */
}

.container {
  padding: 0;
  position: relative; /* 新增：作为绝对定位子元素的定位上下文 */
  height: 100%; /* 新增：填充父元素（page）高度 */
}

.search-bar {
  padding: 20rpx 30rpx 10rpx;
  background: linear-gradient(to right, #1E90FF, #6495ED);
}

.search-input {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 48rpx;
  padding: 0 30rpx;
  height: 80rpx;
  box-shadow: 0 8rpx 20rpx rgba(30, 144, 255, 0.3);
}

.search-logo {
  width: 48rpx;
  height: 48rpx;
  margin-right: 16rpx;
}

.app-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-right: 24rpx;
  white-space: nowrap;
}

.search-input .icon-search {
      font-size: 36rpx;
      color: #888;
      margin-right: 15rpx;
    }

.search-input .placeholder {
  font-size: 28rpx;
  color: #999999;
  flex: 1;
}

.content-area {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: scroll; /* 使content-area内部可滚动 */
  background-color: #F5F6FA;
  z-index: 1; /* 新增：设置z-index确保层叠顺序 */
  width: 100%; /* 新增：明确设置宽度 */
}

.banner-swiper {
  width: 100%;
  height: 300rpx;
  position: relative;
  z-index: 1;
  margin-top: 0; /* 调整为0，因为content-area已处理padding */
}

.banner-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.banner-image {
  width: 100%;
  height: 100%;
  display: block;
}

.banner-title {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 32rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  color: #FFFFFF;
  font-size: 32rpx;
  font-weight: bold;
}

.consultation-card {
  margin: 20rpx 32rpx;
  background-color: #dbeafe;
  border-radius: 16rpx;
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 28rpx;
  color: #1e3a8a;
  display: block;
}

.card-subtitle {
  font-size: 24rpx;
  color: #1d4ed8;
  margin-top: 8rpx;
  display: block;
}

.contact-btn {
  background-color: #4B7BFF;
  color: #FFFFFF;
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  border-radius: 9rpx;
  border: none;
  margin: 4rpx 2rpx; /* 按钮外边距 */
}

/* 按钮点击效果 */
.contact-btn:active {
  opacity: 0.8;
}

/* 城市显示效果 */
/* .city-picker {
	z-index: 999;
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	max-height: 80%;
	overflow-y: auto;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	transition: transform 0.3s ease;
} */

.quick-functions-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 4列布局 */
  gap: 20rpx; /* 间距 */
  padding: 32rpx;
  background-color: #FFFFFF;
  margin-top: 20rpx; /* 与上方轮播图的间距 */
  border-radius: 16rpx;
  margin-left: 32rpx;
  margin-right: 32rpx;
  box-shadow: 0rpx 0rpx 3.5rpx rgba(0, 0, 0, 0.1);
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
}

.func-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 12rpx;
  font-size: 40rpx; /* Icon size */
}

.func-image {
  width: 100%;
  height: 100%;
  display: block;
}

/* 新增图片图标的样式 */
.func-icon-image {
  background-color: transparent !important; /* 确保背景色透明 */
  border-radius: 0 !important; /* 移除圆角，让图片自然填充 */
}

.func-name {
  font-size: 24rpx;
  color: #333333;
  text-align: center;
  white-space: nowrap;
}

/* 新增的背景颜色类，与现有department-grid的背景颜色区分开，保持视觉统一性 */
.func-icon.bg-blue-light { background-color: #e6f7ff; color: #1890ff; }
.func-icon.bg-green-light { background-color: #f6ffed; color: #52c41a; }
.func-icon.bg-orange-light { background-color: #fff7e6; color: #fa8c16; }
.func-icon.bg-purple-light { background-color: #f9f0ff; color: #722ed1; }
.func-icon.bg-pink-light { background-color: #fff0f6; color: #eb2f96; }
.func-icon.bg-red-light { background-color: #fff1f0; color: #f5222d; }
.func-icon.bg-teal-light { background-color: #e0ffef; color: #13c2c2; }
.func-icon.bg-cyan-light { background-color: #e0faff; color: #13a8a8; }

.recommendation-area {
  background-color: #F5F6FA;
  padding: 20rpx 0; /* Padding around the entire recommendation area */
}

.recommendation-section {
  background-color: #FFFFFF;
  margin: 20rpx 32rpx; /* 调整左右外边距，使卡片与屏幕边缘有更大间距 */
  border-radius: 20rpx; /* 增大圆角 */
  box-shadow: 0rpx 8rpx 20rpx rgba(0, 0, 0, 0.08); /* 增强阴影效果，使其更有立体感 */
  padding: 32rpx; /* 保持内边距 */
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx; /* 增大标题与内容的间距 */
}

.section-title {
  font-size: 36rpx; /* 增大标题字体 */
  font-weight: bold;
  color: #333333;
}

.more-link {
  font-size: 26rpx; /* 调整查看更多字体大小 */
  color: #4B7BFF;
  font-weight: 500; /* 增加字体粗细 */
}

.section-content {
  min-height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.no-data-placeholder {
  font-size: 28rpx;
  color: #999999;
}

.recommendation-list {
  display: flex;
  flex-direction: column;
  gap: 30rpx; /* 增大列表项之间的间距 */
}

.list-item {
  display: flex;
  background-color: #FFFFFF;
  border-radius: 16rpx; /* 列表项圆角 */
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05); /* 调整列表项阴影 */
  padding: 28rpx; /* 调整列表项内边距 */
  align-items: center;
  transition: transform 0.2s ease-in-out; /* 添加过渡效果 */
}

.list-item:active { /* 添加点击效果 */
  transform: translateY(2rpx);
}

.item-image {
  width: 180rpx; /* 增大图片尺寸 */
  height: 180rpx;
  border-radius: 16rpx; /* 调整图片圆角 */
  margin-right: 28rpx; /* 调整图片与文本间距 */
  flex-shrink: 0;
  object-fit: cover; /* 确保图片覆盖区域 */
}

.item-image.avatar {
  width: 140rpx; /* 增大头像尺寸 */
  height: 140rpx;
  border-radius: 70rpx; /* 圆形头像 */
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.item-info.no-image {
  margin-left: 0;
}

.item-name {
  font-size: 34rpx; /* 增大名称字体 */
  font-weight: bold;
  color: #333333;
  margin-bottom: 10rpx;
}

.item-detail {
  font-size: 28rpx; /* 调整详情字体大小 */
  color: #666666;
  margin-bottom: 6rpx;
}

.item-snapshot {
  font-size: 26rpx;
  color: #777777;
  margin-bottom: 6rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
}

.item-address {
  font-size: 26rpx; /* 调整地址字体大小 */
  color: #999999;
}

.item-count {
  font-size: 26rpx;
  color: #999999;
  margin-top: 6rpx;
}

.item-name-title {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.item-title {
  font-size: 26rpx; /* 调整职称字体大小 */
  color: #4B7BFF; /* 调整职称颜色 */
  background-color: #E6F0FF; /* 调整职称背景色 */
  padding: 6rpx 16rpx;
  border-radius: 8rpx; /* 调整职称圆角 */
  margin-left: 16rpx;
}

.item-specialty {
  font-size: 26rpx; /* 调整擅长字体大小 */
  color: #777777; /* 调整颜色 */
  margin-top: 6rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5; /* 增加行高 */
}
</style>